<?php


namespace Biz\model\advertisement;

use Doraemon\tools\WorkWeChat;

class MHhzPositionPreview extends MBaseDbModel
{
    const _CONFIG_FILE_ = 'db_position';

    const _CONFIG_SELECT_ = 'db_position';

    const _DATABASE_ = 'hhz_position';

    const _TABLE_NAME = 'hhz_position_preview';

    const IS_DELETED_NO = 0;
    const IS_DELETED_YES = 1;

    public static function updateByPositionRelationId($positionId, $projectId, $projectRelationId, $userIds, $pos)
    {
        if (!$positionId || !$projectId || !$projectRelationId) {
            return;
        }

        $existedUserIds = self::getUserIdsByPositionRelationId($projectRelationId);
        $wxUserId = MHhzAdmin::getWxUserIdByUserId(array_merge($existedUserIds, $userIds));
        $projectInfo = MPositionProject::get('project_name', ['id' => $projectId]);
        $projectRelationInfo = MPositionProjectRelations::get('ad_id', ['id' => $projectRelationId]);
        $adTypeInfo = MPositionAdType::get('type_name', ['id' => $projectRelationInfo['ad_id']]);
        $endTime = date('Y-m-d H:i:s', time() + 3600);
        $startTime = date('Y-m-d H:i:s');

        $needToDelete = array_diff($existedUserIds, $userIds);
        if ($needToDelete) {
            $where = [
                'project_relation_id' => $projectRelationId,
                'user_id' => $needToDelete,
            ];
            self::update(['is_deleted' => self::IS_DELETED_YES, 'updated_at' => $startTime], $where);
        }

        $needToInsert = array_diff($userIds, $existedUserIds);
        if ($needToInsert) {
            $insertData = [];

            foreach ($needToInsert as $d) {
                $insertData[] = [
                    'project_id' => $projectId,
                    'project_relation_id' => $projectRelationId,
                    'position_id' => $positionId,
                    'user_id' => $d,
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'is_deleted' => self::IS_DELETED_NO,
                    'pos' => $pos
                ];
            }
            self::insert($insertData);
        }

        $needToUpdate = array_diff($existedUserIds, $needToDelete);

        if ($needToUpdate) {
            $where = [
                'project_relation_id' => $projectRelationId,
                'user_id' => $needToUpdate,
            ];
            self::update(['end_time' => $endTime, 'updated_at' => $startTime], $where);
        }

//        if ($needToDelete) {
//            $content = "您关闭了「{$projectInfo['project_name']}」-「{$adTypeInfo['type_name']}」的预览。";
//            self::sendMsg(self::getWxUserIdByUserId($wxUserId, $needToDelete), $content);
//        }
//
//        if ($needToInsert) {
//            $content = "您开起了「{$projectInfo['project_name']}」-「{$adTypeInfo['type_name']}」的预览，有效期30分钟，请尽快核对信息是否正确";
//            self::sendMsg(self::getWxUserIdByUserId($wxUserId, $needToInsert), $content);
//        }
//
//        if ($needToUpdate) {
//            $content = "您更新了「{$projectInfo['project_name']}」-「{$adTypeInfo['type_name']}」的预览，有效期30分钟，请尽快核对信息是否正确";
//            self::sendMsg(self::getWxUserIdByUserId($wxUserId, $needToUpdate), $content);
//        }
    }

    public static function closeByPositionRelationId($projectRelationId)
    {
        if (!$projectRelationId) {
            return;
        }
        $where = [
            'project_relation_id' => $projectRelationId,
        ];
        self::update(['is_deleted' => self::IS_DELETED_YES, 'updated_at' => date('Y-m-d H:i:s')], $where);

        //$existedUserIds = self::getUserIdsByPositionRelationId($projectRelationId);
        //$wxUserId = Admin::getWxUserIdByUserId($existedUserIds);
        //$projectInfo = PositionProject::get('project_name', ['id' => $projectId]);
        //$projectRelationInfo = PositionProjectRelations::get('ad_id', ['id' => $projectRelationId]);
//        if () {
//
//            $content = "您关闭了「项目名」-「资源位名称」的预览。";
//            self::sendMsg(self::getWxUserIdByUserId($wxUserId, $existedUserIds), $content);
//        }
    }

    public static function getUserIdsByPositionRelationId($projectRelationId)
    {
        if (!$projectRelationId) {
            return [];
        }

        return self::select("user_id", [
            'project_relation_id' => $projectRelationId,
            'is_deleted' => self::IS_DELETED_NO,
        ]);
    }

    public static function getEndTimeByPositionRelationIds($projectRelationId)
    {
        if (!$projectRelationId) {
            return [];
        }

        $res = self::select("*", [
            'project_relation_id' => $projectRelationId,
            'is_deleted' => self::IS_DELETED_NO,
            'end_time[>]' => date('Y-m-d H:i:s')
        ]);

        return $res ? array_column($res, 'end_time', 'project_relation_id') : [];
    }

    public static function getAvailableProjectWithUserIdAndPositionId($userId, $positionId)
    {
        $where = [
            'user_id' => $userId,
            'position_id' => $positionId,
            'end_time[>]' => date('Y-m-d H:i:s'),
            'is_deleted' => self::IS_DELETED_NO,
        ];

        return self::select('project_relation_id', $where);
    }

    public static function getByProjectId($projectId)
    {
        if (!$projectId) {
            return [];
        }
        $where = [
            'project_id' => $projectId,
            'end_time[>]' => date('Y-m-d H:i:s'),
            'is_deleted' => self::IS_DELETED_NO,
        ];

        return self::select('*', $where);
    }

    private static function getWxUserIdByUserId($wxUserIds, $userIds)
    {
        if (!$wxUserIds || !$userIds) {
            return [];
        }

        $t = [];
        foreach ($userIds as $userId) {
            if (isset($wxUserIds[$userId])) {
                $t[] = $wxUserIds[$userId];
            }
        }
        return $t;
    }
    private static function sendMsg($wxUserId, $content)
    {
        $param = [
            'touser' => implode("|", $wxUserId),
            'content' => $content,
            'agentid' => WorkWeChat::AGENT_1000066,
        ];

        \Doraemon\tools\Curl::Request('post', WorkWeChat::WECHAT_NOTICE_URL, ['form_params' => $param]);
    }
}
